//
//  SettingViewController.m
//  OurWallet
//
//  Created by 小肥羊 on 15/12/29.
//  Copyright © 2015年 小肥羊. All rights reserved.
//

#import "SettingViewController.h"

#pragma mark - 全局常量
NSString *const FamilyOperationLeave = @"离开";
NSString *const FamilyOperationCreate = @"创建";
NSString *const FamilyOperationJoin = @"加入";

@interface SettingViewController ()

@property (weak, nonatomic) IBOutlet UITextField *familyTest;
@property (weak, nonatomic) IBOutlet UIButton *familyButton;
@property (weak, nonatomic) IBOutlet UILabel *familyInfoLabel;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitle:[UserInfoModel sharedManager].username];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showUI) name:nUserInfoChange object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self showUI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nUserInfoChange object:nil];
}

#pragma mark - 显示
- (void)showUI
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (USERINFO.familyName.length > 0) {
            [self showFamily];
        } else {
            [self showNoFamily];
        }
    });
}
- (void)showFamily
{
    [self.familyTest setText:[UserInfoModel sharedManager].familyName];
    [self.familyTest setEnabled:NO];
    [self.familyButton setTitle:FamilyOperationLeave forState:UIControlStateNormal];
    [self.familyButton setEnabled:YES];
    NSString *familyBuddy = @"小伙伴:";
    for (NSDictionary *dict in [UserInfoModel sharedManager].familyBuddy) {
        familyBuddy = [NSString stringWithFormat:@"%@ %@",familyBuddy,dict[@"username"]];
    }
    NSLog(@"%@",familyBuddy);
    [self.familyInfoLabel setText:familyBuddy];
}
- (void)showNoFamily
{
    [self.familyTest setText:@""];
    [self.familyTest setEnabled:YES];
    [self.familyButton setTitle:FamilyOperationCreate forState:UIControlStateNormal];
    [self.familyButton setEnabled:NO];
    [self.familyInfoLabel setText:@"还没有小伙伴哦，快创建Family吧"];
}

#pragma mark - 操作
- (IBAction)clickBackground:(id)sender {
    [self.view endEditing:YES];
}

- (IBAction)clickFamilyButton:(id)sender {
    NSString *familyOperation = self.familyButton.titleLabel.text;
    if ([familyOperation isEqualToString:FamilyOperationLeave]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要离开？" preferredStyle:UIAlertControllerStyleAlert];
        // Create the actions.
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"取消");
        }];
        UIAlertAction *leaveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self addProgressHud];
            __weak typeof(self) _WeakSelf = self;
            BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
            [bquery getObjectInBackgroundWithId:USERINFO.objectId block:^(BmobObject *object,NSError *error){
                if (!error) {
                    if (object) {
                        BmobObject *user = [BmobObject objectWithoutDatatWithClassName:object.className objectId:object.objectId];
                        [user setObject:@"" forKey:@"familyName"];
                        [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                            [_WeakSelf removeProgressHud];
                            if (isSuccessful) {
                                [MBProgressHUD showSuccessWithText:@"已离开"];
                            } else {
                                [MBProgressHUD showErrorWithText:error.userInfo[@"error"]];
                            }
                        }];
                    }
                } else {
                    [_WeakSelf removeProgressHud];
                    [MBProgressHUD showErrorWithText:@"离开失败"];
                }
            }];
        }];
        // Add the actions.
        [alertController addAction:cancleAction];
        [alertController addAction:leaveAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if ([familyOperation isEqualToString:FamilyOperationCreate] || [familyOperation isEqualToString:FamilyOperationJoin]) {
        [self addProgressHud];
        __weak typeof(self) _WeakSelf = self;
        BOOL isCreate = [familyOperation isEqualToString:FamilyOperationCreate];
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
        [bquery getObjectInBackgroundWithId:USERINFO.objectId block:^(BmobObject *object,NSError *error){
            if (!error) {
                if (object) {
                    BmobObject *user = [BmobObject objectWithoutDatatWithClassName:object.className objectId:object.objectId];
                    [user setObject:self.familyTest.text forKey:@"familyName"];
                    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        [_WeakSelf removeProgressHud];
                        if (isSuccessful) {
                            if (isCreate) {
                                [MBProgressHUD showSuccessWithText:@"创建成功"];
                            } else {
                                [MBProgressHUD showSuccessWithText:@"加入成功"];
                            }
                        } else {
                            [MBProgressHUD showErrorWithText:error.userInfo[@"error"]];
                        }
                    }];
                }
            } else {
                [_WeakSelf removeProgressHud];
                if (isCreate) {
                    [MBProgressHUD showErrorWithText:@"创建失败"];
                } else {
                    [MBProgressHUD showErrorWithText:@"加入失败"];
                }
            }
        }];
    }
}


- (IBAction)clickLoginOut:(id)sender {
    [UserInfoModel sharedManager].login = NO;
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 键盘代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.familyTest]) {
        [self.familyButton setEnabled:NO];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField isEqual:self.familyTest]) {
        if (textField.text.length > 0) {
            BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
            [bquery whereKey:@"familyName" equalTo:textField.text];
            [bquery countObjectsInBackgroundWithBlock:^(int number,NSError  *error){
                if (number > 0) {
                     [self.familyButton setTitle:FamilyOperationJoin forState:UIControlStateNormal];
                     [self.familyButton setEnabled:YES];
                 } else {
                     [self.familyButton setTitle:FamilyOperationCreate forState:UIControlStateNormal];
                     [self.familyButton setEnabled:YES];
                 }
            }];
        } else {
            [self.familyButton setTitle:FamilyOperationCreate forState:UIControlStateNormal];
            [self.familyButton setEnabled:NO];
        }
    }
}



@end
